<?php

namespace App\Http\Controllers\Reception\User;

use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Crypt;
use Illuminate\Support\Facades\Cache;
use Illuminate\Http\Request;
//用户模块
class UserController extends Controller
{
    //完善微信用户信息
    public function wxUserLogin(Request $request)
    {
        $map['setting_id'] = 1;
        $info = DB::table('setting')->where($map)->first();
        $info->value = json_decode($info->value, true);
        $Appid = $info->value[0]['value'];
        $AppSecret =$info->value[1]['value'];
        $userInfo = json_decode(htmlspecialchars_decode($request->input('userinfo')),true);
        $code = $request->input('code');
        $url = 'https://api2.weixin.qq.com/sns/jscode2session?appid=' . $Appid . '&secret=' . $AppSecret . '&js_code=' . $code . '&grant_type=authorization_code';
        $res = request_get($url);
        $res = json_decode($res, true);
        if ($res['openid']) {
            $user_map['wx_open_id'] = $res['openid'];
            $user_msg = DB::table('user')->where($user_map)->first();
            if ($user_msg) {
                $user_data['nickName'] = $userInfo['nickName'];
                $user_data['avatarUrl'] = $userInfo['avatarUrl'];
                DB::table('user')->where($user_map)->update($user_data);
                $data = success();
                $data['userid'] = $user_msg->user_id;
                $data['token'] = $this->create_token($user_msg->user_id);
            } else {
                $user_data['wx_open_id'] = $res['openid'];
                $user_data['nickName'] = $userInfo['nickName'];
                $user_data['avatarUrl'] = $userInfo['avatarUrl'];
                $user_data['balance'] = 0;
                $user_data['integral'] = 0;
                $user_data['monetary'] = 0;
                $user_data['gender'] = intval($userInfo['gender']);
                $user_data['country'] = $userInfo['country'];
                $user_data['province'] = $userInfo['province'];
                $user_data['city'] = $userInfo['city'];
                $user_data['address_id'] = 0;
                $user_data['create_time'] = time();
                $user_data['update_time'] = time();
                $user_data['merchant_id'] = 1;
                $userid = DB::table('user')->insertGetId($user_data);
                if ($userid) {
                    $data = success();
                    $data['userid'] = $userid;
                    $data['token'] = $this->create_token($userid);
                } else {
                    $data = fail();
                }
            }
        }
        return $data;
    }

    private function decryptData($sessionKey, $encryptedData, $iv, &$data)
    {
        $setting_map['setting_id'] = 1;
        $info = DB::table('setting')->where($setting_map)->first();
        $info->value = json_decode($info->value, true);
        $appid = $info->value[0]['value'];
        // $appid = 'wxd4d7951f0b2120b8';
        if (strlen($sessionKey) != 24) {
            return fail();
        }
        $aesKey = base64_decode($sessionKey);


        if (strlen($iv) != 24) {
            return fail();
        }
        $aesIV = base64_decode($iv);

        $aesCipher = base64_decode($encryptedData);

        $result = openssl_decrypt($aesCipher, "AES-128-CBC", $aesKey, 1, $aesIV);

        $dataObj = json_decode($result);
        if ($dataObj  == NULL) {
            return fail();
        }
        if ($dataObj->watermark->appid != $appid) {
            return fail();
        }
        $data = $result;
        return $data;
    }


    //激励视频奖励发放
    // public function user
    //生产凭证
    public function create_token($user_id = 0)
    {
        $appsecret = 'VXyZ50Dc$^jNvIFt';
        //生产token
        $appid = $user_id . 'reception';
        Cache::put($appid, $user_id);
        $ori_str = Cache::get($appid . '_' . $appsecret);
        if (!$ori_str) {
            //重新获取就把以前的token删除
            Cache::forget($ori_str);
            //这里是token产生的机制
            $nonce = createNoncestr(32);
            $tmpArr = array($nonce, $appid, $appsecret);
            sort($tmpArr, SORT_STRING);
            $tmpStr = implode($tmpArr);
            $tmpStr = sha1($tmpStr);
            Cache::put($appid . '_' . $appsecret, $tmpStr, 7200);
            Cache::put($tmpStr, $appid . '_' . $appsecret, 7200);
            return $tmpStr;
            //这里做了缓存 'a'=>b 和'b'=>a格式的缓存
        } else {
            return $ori_str;
        }
    }

    // 获取用户信息
    public function getUserInfo(Request $request){
        $token = $request->query('token');
        //验证权限
        $verifytoken = verifytokens($token);
        if (is_array($verifytoken)) {
            return $verifytoken;
        }
        $map['user_id']=$verifytoken;
        $info=DB::table('user')->where($map)->select('avatarUrl','nickName')->first();
        if(empty($info)){
            $data=fail();
        }else{
            $data=success();
            $data['data']=$info;
        }
        return $data;
    }
}
